//
//  NewsSearchResultViewController.m
//  pushNewsManager
//
//  Created by Jobs on 8/6/17.
//  Copyright © 2017 com.Iori. All rights reserved.
//

#import "NewsSearchResultViewController.h"
#import "CommonTableViewCell.h"
#import "Header.h"
#import "UnCheckArtSearchApi.h"
#import "CheckArtSearchApi.h"
#import "NewsEntity.h"
#import "DeleteArtApi.h"
#import "SetArtStarApi.h"
#import "NewsDetailViewController.h"
#import "SetArtApproveStatusApi.h"

@interface NewsSearchResultViewController ()
@property (strong, nonatomic) NSArray<NewsEntity*> *dataSource;
@end

@implementation NewsSearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.estimatedRowHeight = 44; // some constant value
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    WS(weakself);
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakself loadNewsDataFromServerWithCompleteBlock:^(BOOL finished){
            [weakself.tableView.pullToRefreshView stopAnimating];
        }];
    }];
    self.tableView.pullToRefreshView.textColor = [UIColor whiteColor];
    self.tableView.pullToRefreshView.arrowColor = [UIColor whiteColor];
    self.tableView.pullToRefreshView.activityIndicatorViewColor = [UIColor whiteColor];
    [self.tableView triggerPullToRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}



#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if([segue.identifier isEqualToString:@"newsDetailSegue"])
    {
        NSInteger iIndex = ((NSIndexPath*)sender).section;
        NewsEntity *entity = self.dataSource[iIndex];
        NewsDetailViewController *vc = segue.destinationViewController;
        vc.news = entity;
        vc.iRowIndex = iIndex;
        vc.parentVCTable = self.tableView;
        vc.parentVC = self;
    }
}


#pragma mark - load data -
-(void)loadNewsDataFromServerWithCompleteBlock:(void (^)(BOOL finished))success
{
    if(self.iSearchType == 0)
    {
        UnCheckArtSearchApi *api = [UnCheckArtSearchApi new];
        api.admin_id = [UserInfo sharedUser].admin.admin_id;
        api.page = 1;
        api.limit = @"1000";
        api.stime = self.stime;
        api.etime = self.etime;
        if(self.searchTitleContent != nil)
        {
            api.title = self.searchTitleContent;
        }
        else if(self.nickname != nil)
        {
            api.nickname = self.nickname;
        }
        else if(self.member_id != nil)
        {
            api.member_id = self.member_id;
        }
        WS(weakSelf);
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request)
         {
             if(success)
             {
                 success(YES);
             }
             if([IoriJsonHelper getErrorCode:request] == 100)
             {
                 __iCurrentPage = 1;
                 weakSelf.dataSource = [NSArray yy_modelArrayWithClass:[NewsEntity class] json:[IoriJsonHelper getDictForKey:@"list" fromDict:request.responseJSONObject]];
                 [weakSelf.tableView reloadData];
             }
         } failure:^(YTKBaseRequest *request) {
             if(success)
             {
                 success(NO);
             }
         }];
    }
    else
    {
        CheckArtSearchApi *api = [CheckArtSearchApi new];
        api.page = 1;
        api.limit = @"1000";
        api.admin_id = [UserInfo sharedUser].admin.admin_id;
        api.stime = self.stime;
        api.etime = self.etime;
        api.mange_admin_id = api.admin_id;
        if(self.searchTitleContent != nil)
        {
            api.title = self.searchTitleContent;
        }
        else if(self.nickname != nil)
        {
            api.nickname = self.nickname;
        }
        else if(self.member_id != nil)
        {
            api.member_id = self.member_id;
        }
        api.channel_id = self.channel_id;
        WS(weakSelf);
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            if([IoriJsonHelper getErrorCode:request] == 100)
            {
                weakSelf.dataSource = [NSArray yy_modelArrayWithClass:[NewsEntity class] json:[IoriJsonHelper getDictForKey:@"list" fromDict:request.responseJSONObject]];
                [weakSelf.tableView reloadData];
                if(success)
                {
                    success(YES);
                }
            }
            else
            {
                if(success)
                {
                    success(NO);
                }
            }
        } failure:^(YTKBaseRequest *request) {
            if(success)
            {
                success(NO);
            }
        }];
    }
}

#pragma mark - table delegate -

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section != 0) return 0;
    return 30;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section != 0) return nil;
    UILabel *labTitle = [[UILabel alloc] init];
    labTitle.text = [@"    " stringByAppendingString:[NSString stringWithFormat:@"%li条待审内容搜索结果", self.dataSource.count]];
    labTitle.textColor = [UIColor whiteColor];
    if(_iSearchType == 1)
    {
        labTitle.text = [@"    " stringByAppendingString:[NSString stringWithFormat:@"%li条已审内容搜索结果", self.dataSource.count ]];
    }
    return labTitle;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc] init];
    lab.textColor = [UIColor whiteColor];
    NSString *strTime = self.dataSource[section].art_show_time;//@"2017-07-29 10:13";
    if(strTime.length > 0)
    {
        lab.text = [@"    " stringByAppendingString:strTime];
        if(self.iSearchType == 1)
        {
            if(self.dataSource[section].hot_title)
            {
                lab.text = [[lab.text stringByAppendingString:@"     " ] stringByAppendingString:self.dataSource[section].hot_title];
            }
        }
    }
    else
    {
        lab.text = @"";
    }
    lab.text = [lab.text stringByAppendingFormat:@"        %@/%@", self.dataSource[section].art_good, self.dataSource[section].art_bad];
    lab.font = [UIFont systemFontOfSize:13];
    return lab;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NewsEntity *news = self.dataSource[indexPath.section];
    if(news.art_img.count == 1)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    }
    else if(news.art_img.count > 1)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell4Pic"];
    }
    else if(news.art_img.count == 0)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cellNoPic"];
    }
    
    CommonTableViewCell *__cell = (CommonTableViewCell*)cell;
    __cell.parentTable = tableView;
    __cell.parentVC = self;
    __cell.approvingOrApproved = self.iSearchType;
    [__cell updateContent:self.dataSource[indexPath.section]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  UITableViewAutomaticDimension;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    if(self.iSearchType == 1)
    {
        UITableViewRowAction *action_delete = [UITableViewRowAction
                                               rowActionWithStyle: UITableViewRowActionStyleDefault
                                               title: @"  删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                               {
                                                   [tableView setEditing:NO animated:YES];
                                                   
                                                   DeleteArtApi *api = [DeleteArtApi new];
                                                   api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                   api.art_id = weakSelf.dataSource[indexPath.section].art_id;
                                                   [MessageBox displayLoadingInView:weakSelf.view];
                                                   [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                                                       [MessageBox removeLoading];
                                                       if([IoriJsonHelper getErrorCode:request] == 100)
                                                       {
                                                           NSMutableArray *tempDataSource = [NSMutableArray arrayWithArray:weakSelf.dataSource];
                                                           [tempDataSource removeObjectAtIndex:indexPath.section];
                                                           weakSelf.dataSource = tempDataSource;
                                                           [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                                                       }
                                                       else
                                                       {
                                                           [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                       }
                                                   } failure:^(YTKBaseRequest *request) {
                                                       [weakSelf showMessage:request.description];
                                                       [MessageBox removeLoading];
                                                   }];
                                               }];
        
        UITableViewRowAction *action_jinghua = [UITableViewRowAction
                                                rowActionWithStyle: UITableViewRowActionStyleNormal
                                                title: @"  精华" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                                {
                                                    [tableView setEditing:NO animated:YES];
                                                    SetArtStarApi *api = [SetArtStarApi new];
                                                    api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                    api.art_id = weakSelf.dataSource[indexPath.section].art_id;
                                                    api.star = 3;
                                                    [MessageBox displayLoadingInView:weakSelf.view];
                                                    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                                                        [MessageBox removeLoading];
                                                        if([IoriJsonHelper getErrorCode:request] == 100)
                                                        {
                                                            [weakSelf showMessage:@"设置成功"];
                                                        }
                                                        else
                                                        {
                                                            [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                        }
                                                    } failure:^(YTKBaseRequest *request) {
                                                        [weakSelf showMessage:request.description];
                                                        [MessageBox removeLoading];
                                                    }];
                                                }];
        UITableViewRowAction *action_state = [UITableViewRowAction
                                              rowActionWithStyle: UITableViewRowActionStyleNormal
                                              title: @"  隐藏" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                              {
                                                  [tableView setEditing:NO animated:YES];
                                                  SetArtApproveStatusApi *api = [SetArtApproveStatusApi new];
                                                  api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                  api.art_status = @"4";
                                                  api.art_id = weakSelf.dataSource[indexPath.section].art_id;
                                                  [MessageBox displayLoadingInView:weakSelf.view];
                                                  [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request)
                                                   {
                                                       [MessageBox removeLoading];
                                                       if([IoriJsonHelper getErrorCode:request] == 100)
                                                       {
                                                           [weakSelf showMessage:@"隐藏成功"];
                                                           [weakSelf.tableView triggerPullToRefresh];
                                                       }
                                                       else
                                                       {
                                                           [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                       }
                                                   }
                                                                                   failure:^(YTKBaseRequest *request)
                                                   {
                                                       [weakSelf showMessage:[request responseString]];
                                                       [MessageBox removeLoading];
                                                   }];
                                              }];
        return @[action_delete , action_jinghua, action_state];
    }
    else
    {
        UITableViewRowAction *action_delete = [UITableViewRowAction
                                               rowActionWithStyle: UITableViewRowActionStyleDefault
                                               title: @"  删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                               {
                                                   [tableView setEditing:NO animated:YES];
                                                   
                                                   DeleteArtApi *api = [DeleteArtApi new];
                                                   api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                   api.art_id = weakSelf.dataSource[indexPath.section].art_id;
                                                   [MessageBox displayLoadingInView:weakSelf.view];
                                                   [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                                                       [MessageBox removeLoading];
                                                       if([IoriJsonHelper getErrorCode:request] == 100)
                                                       {
                                                           NSMutableArray *tempDataSource = [NSMutableArray arrayWithArray:weakSelf.dataSource];
                                                           [tempDataSource removeObjectAtIndex:indexPath.section];
                                                           weakSelf.dataSource = tempDataSource;
                                                           [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                                                       }
                                                       else
                                                       {
                                                           [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                       }
                                                   } failure:^(YTKBaseRequest *request) {
                                                       [weakSelf showMessage:request.description];
                                                       [MessageBox removeLoading];
                                                   }];
                                               }];
        UITableViewRowAction *action_state = [UITableViewRowAction
                                              rowActionWithStyle: UITableViewRowActionStyleNormal
                                              title: @"  隐藏" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                              {
                                                  [tableView setEditing:NO animated:YES];
                                                  SetArtApproveStatusApi *api = [SetArtApproveStatusApi new];
                                                  api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                  api.art_status = @"4";
                                                  api.art_id = weakSelf.dataSource[indexPath.section].art_id;
                                                  [MessageBox displayLoadingInView:weakSelf.view];
                                                  [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request)
                                                   {
                                                       [MessageBox removeLoading];
                                                       if([IoriJsonHelper getErrorCode:request] == 100)
                                                       {
                                                           [weakSelf showMessage:@"隐藏成功"];
                                                           [weakSelf.tableView triggerPullToRefresh];
                                                       }
                                                       else
                                                       {
                                                           [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                       }
                                                   }
                                                                                   failure:^(YTKBaseRequest *request)
                                                   {
                                                       [weakSelf showMessage:[request responseString]];
                                                       [MessageBox removeLoading];
                                                   }];
                                              }];
        return @[action_delete , action_state];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    [self performSegueWithIdentifier:@"newsDetailSegue" sender:indexPath];
}


@end
